package ru.urfc.portal.services;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

import ru.urfc.portal.model.Branch;
import ru.urfc.portal.model.SysObject;
import ru.urfc.portal.model.documents.Document;
import ru.urfc.portal.model.documents.DocumentType;

@Table(name = "dms_category")
@Entity
@XmlRootElement(name = "dms-category")
public class DmsCategory extends SysObject {
	public DocumentType doctype;
	public Branch branch;
	public String categoryUuid;
	
	public DmsCategory() {}
	public DmsCategory(DocumentType doctype, Branch branch, String categoryUuid) {
		this.doctype = doctype;
		this.branch = branch;
		this.categoryUuid = categoryUuid; 
	}
	
	public static String getCategoryUuid(EntityManager sys, Document doc) {
		return getCategoryUuid(sys, doc.getClient().getBranch(), doc.getType());
	}

	public static String getCategoryUuid(EntityManager sys, Branch branch, DocumentType docType) {
		String sqlCateg = "select cat from DmsCategory cat where cat.branch = :branch and cat.doctype = :doctype";
		Query query = sys.createQuery(sqlCateg).setParameter("branch", branch).setParameter("doctype", docType);
		//TODO return ((DmsCategory) query.getSingleResult()).categoryUuid;
		List<DmsCategory> cats = (List<DmsCategory>) query.getResultList();
		if (cats.size() > 0) { 
			return cats.get(0).categoryUuid;
		} else {
			return branch.getCode() == "sverd" ? "pstcimlg800fg0000ig7l4ejmijd4r4o" 
					: "pstcimlg800fg0000ig7l3ns31jqgnng";
		}
	} 
	
	public static Branch[] branches = { Branch.SVERD, Branch.KURGAN, null, null, null};
	// Екатеринбург;Курган;Тюмень;Х-Мансийск;Челябинск
	
	public static DmsCategory[] createCategory(DocumentType docType, String semicolonSeparatedCategs){
		List<DmsCategory> result = new ArrayList<DmsCategory>();
		String[] categs = semicolonSeparatedCategs.split(";"); 
		for (int i = 0; i<categs.length; i++) {
			if (branches[i] != null) {
				DmsCategory dmsCateg = new DmsCategory(docType, branches[i], categs[i]);
				result.add(dmsCateg);
			}
		}
		return result.toArray(new DmsCategory[]{});
	}
}
